package libaryinterface.user;

import libaryinterface.interfaceutils.MyDialogDemo;
import pojo.Category;
import pojo.User;
import pojo.vo.BookVo;
import service.BookService;
import service.CategoryService;
import service.UserService;
import service.impl.BookServiceImpl;
import service.impl.CategoryServiceImpl;
import service.impl.UserServiceImpl;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-12-07
 * Time: 16:56
 */
//用户查找界面
public class UserFindInrface extends JFrame{
    int i =0;
    public UserFindInrface(String bookName, String account) throws SQLException {
        //设置窗口
        super("展示界面");

        //1.把图片添加到标签里（把标签的大小设为和图片大小相同），把标签放在分层面板的最底层；
        ImageIcon bg = new ImageIcon("src//picture//excel.jpg");
        JLabel label = new JLabel(bg);
        label.setSize(bg.getIconWidth(),bg.getIconHeight());
        UserFindInrface.super.getLayeredPane().add(label,new Integer(Integer.MIN_VALUE));
        //2.把窗口面板设为内容面板并设为透明、流动布局。
        JPanel p1=(JPanel)UserFindInrface.super.getContentPane();
        p1.setOpaque(false);
        p1.setLayout((new FlowLayout()));

        Container container = this.getContentPane();
        setBounds(500,500,1000,1200);
        // 表头（列名）
        Object[][] rowData = new Object[100][8];
        //记录当前的条数
        BookService bookService = new BookServiceImpl();
        List<BookVo> bookList = bookService.listBookByBookName(bookName);
        String[] columnNames = {" SNID","书名", "作者", " 出版社 ", "剩余数量", "借出数量","总数量","存放地点"};
        for (BookVo book: bookList) {
            //获取信息
            Long snid =  book.getSnid();
            String name = book.getName();
            String author = book.getAuthor();
            String press = book.getPress();
            Long surplusNumber = book.getSurplusNumber();
            Long lendNumber = book.getLendNumber();
            Long allNumber = book.getAllNumber();
            String storagePlace = book.getStoragePlace();
            //放入表格数组中
            rowData[i][0] = snid;
            rowData[i][1] = name;
            rowData[i][2] = author;
            rowData[i][3] = press;
            rowData[i][4] = surplusNumber;
            rowData[i][5] = lendNumber;
            rowData[i][6] = allNumber;
            rowData[i][7] = storagePlace;
            i++;
        }

        //设置标签
        JLabel label1 = new JLabel("总数量: " + bookList.size());
        label1.setBounds(100,20,150,40);
        label1.setFont(new Font(null, Font.PLAIN, 20));
        label1.setForeground(Color.GREEN);


        // 创建一个表格，指定 表头 和 所有行数据
        JTable table = new JTable(rowData, columnNames);

        // 设置表格内容颜色
        table.setForeground(Color.BLACK);                   // 字体颜色
        table.setFont(new Font(null, Font.CENTER_BASELINE,20));      // 字体样式
        table.setSelectionForeground(Color.DARK_GRAY);      // 选中后字体颜色
        table.setSelectionBackground(Color.YELLOW);     // 选中后字体背景
        table.setGridColor(Color.GRAY);                     // 网格颜色
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();//单元格渲染器
        tcr.setHorizontalAlignment(JLabel.CENTER);//居中显示
        table.setDefaultRenderer(Object.class, tcr);//设置渲染器
        // 设置表头
        table.getTableHeader().setFont(new Font(null, Font.BOLD, 25));  // 设置表头名称字体样式
        table.getTableHeader().setForeground(Color.RED);                // 设置表头名称字体颜色
        table.getTableHeader().setResizingAllowed(true);               // 设置不允许手动改变列宽
        table.getTableHeader().setReorderingAllowed(false);             // 设置不允许拖动重新排序各列

        // 设置行高
        table.setRowHeight(40);

        // 第一列列宽设置为40
        table.getColumnModel().getColumn(0).setPreferredWidth(40);

        // 设置滚动面板视口大小（超过该大小的行数据，需要拖动滚动条才能看到）
        table.setPreferredScrollableViewportSize(new Dimension(400, 300));
        // 把 表格 放到 滚动面板 中（表头将自动添加到滚动面板顶部）
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(240,180,1000,600);

        UserService userService = new UserServiceImpl();
        CategoryService categoryService = new CategoryServiceImpl();
        //修改按钮
        Font font = new Font("隶书",Font.PLAIN,24);
        JButton button = new JButton("借阅");
        button.setFont(font);
        button.setBounds(700,850,100,80);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    //获取当前的行列数
                    int index = 0;  //1
                    index = table.getSelectedRow();
                    if( index>=i) {
                        new MyDialogDemo("请选中相应行!");
                        return;
                    }
                    //判断书籍是否被借完
                    if ( (Long)rowData[index][4] == 0) {
                        new MyDialogDemo("书籍已借完");
                        return ;
                    }
                    User user = userService.getUserByAccount(account);
                    //获取用户当前已借书的数量
                    Long alreadyLendNumber = user.getAlreadyNumber();
                    //获取用户的身份
                    Category category = categoryService.getCategoryByAccount(account);
                    Long maxLendTIme = category.getLoanTime();   //该身份的最大借阅天数
                    Long maxLendNumber = category.getLoanNumber();//该身份的最大借阅数量
                    Long surplusLendNumber = maxLendNumber-alreadyLendNumber;
                    Long bookId = (Long)rowData[index][0];
                    //判断借书数量是否超出上限
                    //判断借书时长是否超过身份应有的时长
                    //书籍未借出, 执行借书的操作,在借阅记录表中添加 借书记录
                    new UserLendtimeInterface(bookId,account,maxLendTIme,surplusLendNumber);
                } catch (Exception ex){

                    System.out.println("借阅失败");
                }
            }

        });

        //刷新按钮
        JButton button4 = new JButton("刷新");
        button4.setBounds(1300,100,100,50);
        button4.setFont(font);
        container.add(button4);
        button4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                UserFindInrface.super.dispose();
                try {
                    new UserFindInrface(bookName,account);
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        container.add(label1);
        container.add(button);
        // 添加 滚动面板 到 内容面板
        container.add(scrollPane);
        //获得容器
        container.setBackground(new Color(50, 144, 236));
        container.setLayout(null);
        //container.setVisible(true);
        setBounds(180,1,1500,1200);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

}
